<template>
  <div v-show="!loading" class="page-box">
    <div class="item-box  article-box" v-if="articleInfo">
      <div class="title">{{articleInfo.headline}}</div>
      <div class="info-box">
        <div class="left">
          <img :src="articleInfo.avatar">
        </div>
        <div class="middle">
          <span>{{articleInfo.author}}</span>
          <div>
            <span>{{dateFormat(articleInfo.createTime,'yyyy/MM/dd')}}</span>
            <span>·</span>
            <span>点赞</span>
            <span>{{articleInfo.praise}}</span>
          </div>
        </div>
      </div>
      <div class="short-content">
        <span class="red">摘要：</span>
        <span>{{articleInfo.summary}}</span>
      </div>
      <div class="cover">
        <img v-if="articleInfo.imgUrl" :src="articleInfo.imgUrl">
      </div>
      <div class="detail" v-html="articleInfo.detail"></div>
      <div class="up-rewoard-box">
        <div>
          <div class="img-box" v-if="articleInfo.isPraise">
            <img src="../assets/uped.png">
          </div>
          <div class="img-box" v-else  @click="up()" >
            <img src="../assets/up.png">
          </div>
          <div>赞</div>
        </div>
        <!-- <div>
          <div class="img-box" @click="ctrlRewardAmountBox(true)">
            <img src="../assets/reward.png">
          </div>
          <div>打赏</div>
        </div> -->
      </div>
      <div class="reward-amount-box" v-show="rewardAmountBoxFlag">
        <div class="main">
          <div class="reward-title">
            <span>打赏</span>
            <span class="close-btn" @click="ctrlRewardAmountBox(false)">×</span>
          </div>
          <div class="amount-box">
            <div class="amount-box-item">
              <template v-for="(item, index) in amountArr">
              <span v-if="index < 3"
              :key="item"
              :class="{'on': amountSelected === item}"
              @click="selectAmount(item)">￥{{item}}</span>
              </template>
            </div>
            <div class="amount-box-item">
              <template v-for="(item, index) in amountArr">
              <span v-if="index > 2"
              :key="item"
              :class="{'on': amountSelected === item}"
              @click="selectAmount(item)">￥{{item}}</span>
              </template>
            </div>
          </div>
          <div class="custom-amount">
            <input type="number" class="input-box" placeholder="自定义金额" v-model="inputAmount" @focus="inputFocus()">
            <div :class="{'disabled':amountSelected < 0 && inputAmount === ''}" @click="doReward()">打赏</div>
          </div>
        </div>
      </div>
      <div class="tips">
        文章内容仅供参考，不构成投资建议，投资有风险，入市需谨慎！
      </div>
      <div class="keyword-box">
        <template v-if="articleInfo.keyword">
          <span v-for="item in articleInfo.keyword.split(',')" :key="item">{{item}}</span>
        </template>
      </div>
    </div>
    <Recommend v-if="recommendList.length > 0" class="item-box" :list="recommendList" type="cms"/>
  </div>
</template>

<script>
import * as api from '@/utils/api'
import { dateFormat } from '@/utils/date'
import cookie from '@/utils/cookie'
import { operationType } from '@/utils/assist'
import { Toast, Indicator } from 'mint-ui'
import { getToken, setToken } from '@/utils/auth'
import Recommend from '@/components/recommend-article'
export default {
  name: 'index',
  components: {
    Recommend
  },
  data () {
    return {
      loading: true,
      articleInfo: {},
      rewardAmountBoxFlag: false,
      amountArr: [10, 20, 50, 66, 88, 100],
      inputAmount: '',
      amountSelected: 10,
      deviceType: null,
      // 推荐阅读
      recommendList: [],
      siteId: 0
    }
  },
  watch: {
    '$route' (to, val) {
      this.id = this.$route.params.id
      this.siteId = this.$route.params.siteId
      this.initData()
      return val
    }
  },
  created () {
    this.id = this.$route.params.id
    this.siteId = this.$route.params.siteId
    document.title = '文章详情'
    this.getTokenFromApp()
    this.initFnForApp()
  },
  methods: {
    dateFormat: dateFormat,
    /**
     * 初始化页面数据
     */
    initData () {
      Indicator.open()
      this.loading = true
      Promise.all([
        this.getArticleInfo(),
        this.getRecommendArticleInfo()
      ]).then((res) => {
        let articleData = res[0]
        if (articleData) {
          this.articleInfo = articleData
        }
        let recommendData = res[1]
        if (recommendData) {
          let tempList = recommendData.data
          let index = tempList.findIndex((item) => {
            return item.articleId + '' === this.id
          })
          if (index >= 0) {
            tempList.splice(index, 1)
          }
          this.recommendList = tempList
        }
        Indicator.close()
        this.loading = false
      }).catch((e) => {
        Indicator.close()
        console.log(e)
      })
    },
    ctrlRewardAmountBox (flag) {
      this.rewardAmountBoxFlag = flag
    },
    selectAmount (item) {
      this.amountSelected = item
    },
    inputFocus () {
      this.amountSelected = -1
    },
    doReward () {
      let amount = 0
      if (this.amountSelected > -1) {
        amount = this.amountSelected
      } else {
        amount = this.inputAmount
      }
      let reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
      if (!reg.test(amount)) {
        Toast('请输入正确的金额')
        return
      }
      let rewardInfo = {
        payType: 'alipay',
        payAmount: amount,
        businessId: 1
      }
      let str = JSON.stringify(rewardInfo)
      if (this.deviceType.android) {
        if (typeof window.androidApp !== 'undefined') {
          switch (rewardInfo.payType) {
            case 'alipay':
              Toast('向android app发送支付支付宝支付信息：' + str)
              window.androidApp.aliPay(str)
              break
            case 'wx':
              Toast('向android app发送微信支付信息：' + str)
              window.androidApp.wxPay(str)
              break
            default:
              break
          }
        }
      } else {
        if (typeof window.iosApp !== 'undefined') {
          switch (rewardInfo.payType) {
            case 'alipay':
              Toast('向ios app发送支付支付宝支付信息：' + str)
              window.iosApp.aliPay(str)
              break
            case 'wx':
              Toast('向ios app发送微信支付信息：' + str)
              window.iosApp.wxPay(str)
              break
            default:
              break
          }
        }
      }
    },
    async up () {
      try {
        let res = await api.praiseForCmsArticle({
          articleId: this.id
        })
        if (!res) {
          this.articleInfo.isPraise = 1
        }
      } catch (error) {
        Toast('操作失败，' + error.message)
      }
    },
    // 当前文章详情
    async getArticleInfo () {
      try {
        const id = this.$route.params.id
        let params = {
          articleId: id,
          siteId: this.siteId
        }
        let res = await api.getCmsArticleDetail(params) // 计划文章
        return res
      } catch (error) {
        Toast('数据加载失败，' + error.message)
      }
    },
    // 推荐文章列表
    async getRecommendArticleInfo () {
      try {
        let params = {
          pageNum: 1,
          pageSize: 7,
          siteId: this.siteId
        }
        let res = await api.getCmsRecommendArticle(params) // cms文章
        return res
      } catch (error) {
        Toast('数据加载失败，' + error.message)
      }
    },
    // 调用app的方法获取token
    getTokenFromApp () {
      this.deviceType = operationType()
      let token = null
      if (this.deviceType.mobile) {
        if (this.deviceType.android) {
          if (typeof window.androidApp !== 'undefined') {
            token = window.androidApp.getToken()
            this.setTokenAndCookie(token)
          }
          this.initData()
        } else {
          setTimeout(() => {
            if (typeof window.iosApp !== 'undefined') {
              token = window.iosApp.getToken()
            } else {
              this.initData()
            }
          }, 500)
        }
      } else {
        if (!getToken()) {
          token = 'fake test token'
          this.setTokenAndCookie(token)
        }
        this.initData()
      }
    },
    setTokenAndCookie (token) {
      cookie.set('device_id', token)
      setToken(token)
    },
    initFnForApp () {
      window.rewardSuccess = () => {
        Toast('支付成功')
      }
      window.rewardFail = (res) => {
        Toast('支付失败' + res)
      }
      window.receiveTokenFromIOS = (token) => {
        this.setTokenAndCookie(token)
        this.initData()
      }
    }
  }
}
</script>
<style lang="scss" scope>
@import "../style/art-detail";
</style>
